//
//  PictureBrowserCell.swift
//  WeiBoSwift
//
//  Created by rong on 15/7/5.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit
import SDWebImage
import FFAutoLayout

protocol PictureBrowserDelegate: NSObjectProtocol {
    func PictureBrowserDidTap(cell: PictureBrowserCell)
    
    //图片缩放，整个照片浏览器跟着缩放,  参数是缩放比例
    func PictureBrowserDidZooming(scale: CGFloat)
    
    //图片视图完成缩放
    func PictureBrowserEndZoom()
}

class PictureBrowserCell: UICollectionViewCell, UIScrollViewDelegate {
    
    //代理
    weak var cellDelegate: PictureBrowserDelegate?
    
    var imageURL: NSURL? {
    
        didSet {
        
            indicator.startAnimating()
            // 重设 resetScrollview的  偏移属性
            resetScrollview()
            
            //placeholderImage：占位图像，这里设置为 nil
            picImageView.sd_setImageWithURL(imageURL, placeholderImage: nil) { (image, error, _, _) -> Void in
                
                //下载完成后， 自动设置图像尺寸
                //self.picImageView.sizeToFit()    如果这样设置，只能显示图片的一小部分
                //self.picImageView.frame = CGRect(origin: CGPointZero, size: self.picDisplay(image))
                
                self.imagePosition(image)
                
                /* (187.5, 333.5)   (562.5, 333.5) */
                //print(self.center)
                //self.picImageView.center = CGPoint(x: 187.5, y: 333.5)
                
                self.indicator.stopAnimating()
                
            }
        }
    }
    
    // 重设 resetScrollview的  偏移属性
    private func resetScrollview() {
        
        picScrollView.contentOffset = CGPointZero
        picScrollView.contentSize = CGSizeZero
        picScrollView.contentInset = UIEdgeInsetsZero
        
        //！！！！如果不加下面这句＝＝＝》浏览时照片，如果放大第一张照片，滚动到第三张照片再放大缩小会出问题
        // 重设 形变参数
        picImageView.transform = CGAffineTransformIdentity
    }
    
    //设置位置
    private func imagePosition(image: UIImage) {
    
        let size = self.picDisplay(image)
        
        
        //如果是长图
        /*if bounds.height < size.height {
            
            picImageView.frame = CGRect(origin: CGPointZero, size: size)
            //!!!设置了这个之后，scrollview就能滚动了
            picScrollView.contentSize = size
            
        } else {
            
           let y = (self.bounds.height - size.height) * 0.5
            picImageView.frame = CGRect(origin: CGPoint(x: 0, y: y), size: size)
            
            let top = (bounds.height - size.height) * 0.5
            picScrollView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)
        }*/
        
        picImageView.frame = CGRect(origin: CGPointZero, size: size)
        
        // 长图
        if size.height > bounds.height {
            picScrollView.contentInset = UIEdgeInsetsZero
            picScrollView.contentSize = size
        } else {
            let top = (bounds.height - size.height) * 0.5
            picScrollView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)
        }
        
        
    }
    
    //根据图像大小，计算显示尺寸
    private func picDisplay(image: UIImage) -> CGSize {
    
        let scale = image.size.height / image.size.width
        let height = bounds.width * scale
        
        return CGSize(width: bounds.width, height: height)
    }
    
    override init(frame: CGRect) {

        super.init(frame: frame)
        
        //这里面cell 的frame 已经有值了 ，因为collectioview的布局layout的 itemSize 已经设置好了
        
        picScrollView.frame = bounds
        
        addSubview(picScrollView)
        
        picScrollView.delegate = self
        picScrollView.minimumZoomScale = 0.5
        picScrollView.maximumZoomScale = 2.0
        
        //picImageView的大小 以后再设置
        picScrollView.addSubview(picImageView)
        
        addSubview(indicator)
        //indicator.center = center    这样写不行
        indicator.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: nil)
        
        //添加手势
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        picImageView.addGestureRecognizer(tap)
        //如果不设置这个，点击  ImageView 会没有反应
        picImageView.userInteractionEnabled = true
    }

    //点击图片 调用代理方法
    func tapImage() {
        
        cellDelegate?.PictureBrowserDidTap(self)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //UIScrollViewDelegate 代理方法
    
    //告诉scrollview ，缩放谁
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        //return picScrollView   这样会出错！！！，不能缩放自己
        return picImageView
    }
    
    /*
    struct CGAffineTransform {
    var a: CGFloat    缩放
    var b: CGFloat
    var c: CGFloat
    var d: CGFloat    缩放
    var tx: CGFloat   位移
    var ty: CGFloat   位移
    
    a, b, c, d  共同决定旋转
    
    */
    //只要缩放，就会调用这个方法
    func scrollViewDidZoom(scrollView: UIScrollView) {
        
        let scale = picImageView.transform.a
        cellDelegate?.PictureBrowserDidZooming(scale)
    }
    
    //缩放结束，会调用这个方法
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        //缩放结束后，重新计算边距
        /*var offsetX = (scrollView.bounds.width - view!.bounds.width) * 0.5
        if offsetX < 0 {
            offsetX = 0
        }
        
        var offsetY = (scrollView.bounds.height - view!.bounds.height) * 0.5
        if offsetY < 0 {
            offsetY = 0
        }
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)*/
        
        // 根据缩放结束后 view 的 frame 调整视图位置
        var offsetX = (frame.width - view!.frame.width) * 0.5
        offsetX = offsetX < 0 ? 0 : offsetX
        var offsetY = (frame.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        print("gagagagaggagagagag ==>  offsetX:\(offsetX)   offsetY:\(offsetY)")
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        
        //缩放结束，调用协议方法
        cellDelegate?.PictureBrowserEndZoom()
    }
    
    
    //懒加载Cell里面的控件:  一个scrollview，再里面还有一个uiimageview
    private lazy var picScrollView = UIScrollView()
    /*private*/ lazy var picImageView = UIImageView() //关闭他的private， 外面的保存到相册功能需要使用它获取图片
    //菊花控件
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
}
